package com.fan.shop.model.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.fan.shop.services.UserService;

@FacesValidator(value = "usernameValidator")
public class UsernameValidator implements Validator {

	
	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void validate(FacesContext context, UIComponent component, Object value)
			throws ValidatorException {
		
		userService = (UserService)component.getAttributes().get("userService");
		String username = value.toString();
		
		if(userService.hasUser(username))
		{
			FacesMessage message = new FacesMessage();
			message.setDetail("User: " + username + " already exists!");
			throw new ValidatorException(message);
		}
		
		
		
		System.out.println(userService);

	}

}
